#include "remm_sync.h"



lsv_s32_t remm_truncate_send_sync(lsv_volume_proto_t *volume_proto, lsv_s32_t size){
	lsv_s32_t err = 0;
	lsv_s32_t socket_fd = 0;
	lsv_op_type op_type;
lsv_wrlock(&conn_lock);
	socket_fd = remm_connect(volume_proto);
	if(socket_fd < 0){
		DERROR("remm_connect return sock_fd:%d\n", socket_fd);
		err = socket_fd;
		goto EXIT;
	}

	op_type.op_code = LSV_OP_TYPE_MSG | LSV_OP_CODE_TRUNCATE;
	op_type.size = size;
#ifdef LSV
	//sprintf(op_type.path, "%s", volume_proto->path);
#else
	op_type.chkid = ((volume_proto_t *)volume_proto->volume_proto)->chkid;
#endif
	err = write(socket_fd, (lsv_s8_t *)&op_type, sizeof(lsv_op_type));
	if(err != sizeof(lsv_op_type)){
		DERROR("write size : %d not equal the msg size: %lu\n", err, sizeof(lsv_op_type));
		err = -errno;
		close(socket_fd);
		goto EXIT;
	}
	
	DINFO("write success!\n");
	close(socket_fd);
EXIT:
lsv_rwunlock(&conn_lock);
	return 0;
}

lsv_s32_t remm_data_send_sync(lsv_volume_proto_t *volume_proto, lsv_s8_t * buf, lsv_u64_t lba, lsv_s32_t size){
	lsv_s32_t err = 0;
	lsv_s32_t socket_fd = 0;
	lsv_op_type op_type;
	struct linger lin;
lsv_wrlock(&conn_lock);
	socket_fd = remm_connect(volume_proto);
	if(socket_fd < 0){
		DERROR("remm_connect return sock_fd:%d\n", socket_fd);
		err = socket_fd;
		goto EXIT;
	}
#if 1	
	lin.l_onoff = 1;
        lin.l_linger = 15;      /* how many seconds to linger for */
        err = setsockopt(socket_fd, SOL_SOCKET, SO_LINGER, &lin, sizeof(lin));
        if (err == -1) {
                err = -errno;
                goto EXIT;
        }
#endif

	op_type.op_code = LSV_OP_TYPE_DATA | LSV_OP_CODE_WRITE;
	op_type.size = size;
	op_type.offset = lba;
#ifdef LSV
	//sprintf(op_type.path, "%s", volume_proto->path);
#else
	op_type.chkid = ((volume_proto_t *)volume_proto->volume_proto)->chkid;
#endif
	err = write(socket_fd, (lsv_s8_t *)&op_type, sizeof(lsv_op_type));
	if(err != sizeof(lsv_op_type)){
		DERROR("write size : %d not equal the msg size: %lu\n", err, sizeof(lsv_op_type));
		err = -errno;
		close(socket_fd);
		goto EXIT;
	}

	err = write(socket_fd, buf, size);
	if(err != size){
		DERROR("write size : %d not equal the msg size: %d\n", err, size);
		err = -errno;
		close(socket_fd);
		goto EXIT;
	}
	err = read(socket_fd, buf, size);
	if(err > 0){
		if(0 == strcmp("done", (const char *)buf)){
			DINFO("send success!\n");
		}
	}else{
		DERROR("CANNOT RECEIVE DONE..\n");
	}
	
	DINFO("write success!\n");
	close(socket_fd);
EXIT:
lsv_rwunlock(&conn_lock);
	return 0;
}

